//封装axios
//实例化 请求拦截器 响应拦截器
import axios from "axios";
import { getToken } from "./token";
import { history } from "./history";

const http = axios.create({
    baseURL:'http://geek.itheima.net/v1_0',
    timeout:5000
})

//添加请求拦截器
http.interceptors.request.use((config)=>{
    const token = getToken()
    console.log(token,"token")
    if(token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
},(error)=>{
    return Promise.reject(error)
})

//响应拦截器
http.interceptors.response.use((response)=>{
    return response.data
},(error)=>{
    console.log(error,"401-----------")
    //token失效的逻辑判断
    if(error.response.status===401){
        //跳转登录页 
        //reactRouter默认状态下并不支持组件之外完成路由跳转
        history.push('/login')

    }
    return Promise.reject(error)
})

export { http }